<?php

namespace app\index\controller;

use app\api\controller\Xiaohe;
// use app\api\controller\Share;

use app\api\controller\Com;


use app\common\controller\Frontend;
use EasyWeChat\Factory;
use think\Config;
use think\Db;
use think\Session;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    
    public function _initialize()
    {
        parent::_initialize();
        // //班级列表
        // $team_list = Db::name('team_id')->column('*','id');
        // $this->view->assign('team_list',$team_list);

        // halt(1);
        // $user = $this->get_user();
    }


    public function index()
    {
        // $this->redirect('/index/index/index_index');
        // echo "1111";
        return $this->view->fetch();
    }

    /**
     * 获取微信公众号
     *
     * @return void
     */
    public function get_wx_gzh_app()
    {

         $config = [
             'app_id' => Config('site.wx_app_id'),//微信公众号的appid
             'secret' => Config('site.wx_secret'),//微信公众号的密钥
         
             // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
             'response_type' => 'array',
         ];
         
         //微信公众号的方法
         $app = Factory::officialAccount($config);
         return $app;
    }

    /**
     * 获取用户信息，没有授权的自动授权，类似登录
     * 
     * @return void
     */
    public function get_user($re_url=null)
    {
        if($re_url){
            Session::set('re_url',$re_url);
        }
        $app = $this->get_wx_gzh_app();
        $oauth = $app->oauth;

        // 未登录或没openid数据的
        if (empty(Session::get('wechat_user'))) {
            
            $url = $this->request->domain().'/index/index/code';//改成当前类的 访问路径，可以写成封装方法，怕一些用户看不懂
            $oauth->scopes(['snsapi_userinfo'])->redirect($url);//获取用户信息跳转
            //非Tp框架的可能要return
            
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            $oauth->redirect()->send();
            // halt(4);
        }
            
        $user = Session::get('wechat_user');

        $Xiaohe = new Xiaohe;
        // halt($user);
        $Xiaohe->update_user_data($user,Session::get('sharer'));
        $user_data = $Xiaohe->openid_get_user($user['openid']);
        
         
        $ret = $this->auth->direct($user_data['id']);
        $id = $this->auth->id;//getUserinfo();
        // halt($token);
        Session::set('id',$id);

        return $user;
    }


    // 查看学生进场校门
    public function look_image($id=null)
    {
        $this->get_user('/index/index/look_image?id='.$id);
        $user = Db::name('user')->find($this->auth->id);
        $data = Db::name('door_log')->find($id);
        if($data['uid']!=$user['bind_uid']){
            $this->error('非绑定的学生,不能查看');
        }

        if(empty($data['image'])){
            //更新图片
            $Task = new \app\api\controller\Task();
            $Task->get_one_image($id);
            $data = Db::name('door_log')->find($id);
        }
        
        $student = Db::name('student')->where('uid',$data['uid'])->find();

        $this->view->assign('user',$user);
        $this->view->assign('student',$student);
        $this->view->assign('data',$data);
        return $this->view->fetch();
    }

    // 绑定学生
    public function bind_student()
    {
        $user = $this->get_user('/index/index/bind_student');
        
        //提交的绑定数据
        if($this->request->isPost()){
            $data['team_id'] = $this->request->param('team');
            $data['name'] = $this->request->param('name');

            $student = Db::name('student')->where($data)->find();
            if(!$student){
                $this->error('没有该同学');
            }


            $tel =$this->request->param('tel');
            $data['mom_tel'] = $tel;
            $student = Db::name('student')->where($data)->find();
            if($student){
                //修改绑定信息
                Db::name('user')->where('id',$this->auth->id)->update(['bind_uid'=>$student['uid']]);
                Db::name('student')->where('uid',$student['uid'])->update(['mom_id'=>$this->auth->id]);
                $this->success('绑定母亲成功');
                
            }else{
                //查爸爸的手机号
                $data['mom_tel'] = $tel;
                unset($data['mom_tel']);
                $data['dad_tel'] = $tel;
                $student = Db::name('student')->where($data)->find();
                if($student){
                    //修改绑定信息
                    Db::name('user')->where('id',$this->auth->id)->update(['bind_uid'=>$student['uid']]);
                    Db::name('student')->where('uid',$student['uid'])->update(['dad_id'=>$this->auth->id]);
                    $this->success('绑定父亲成功');
                    
                }
            }

            $this->view->assign('student',$student);
        }


        //是否绑定过学生
        $bind_uid = Db::name('user')->where('id',$this->auth->id)->value('bind_uid');
        if($bind_uid){
            //学生数据
            $student = Db::name('student')->where('uid',$bind_uid)->find();
            $this->view->assign('student',$student);
        }


        $team_list = Db::name('team_id')->column('*','id');
        $this->view->assign('user',$user);
        $this->view->assign('title','绑定学生');
        $this->view->assign('team_list',$team_list);
        
       
        return $this->view->fetch();
        halt('bind_student');
    }





  

    /**
     * 我的
     *
     * @return void
     */
    public function me()
    {
        $user = $this->get_user();
        $user = Db::name('user')->find($this->auth->id);

        halt($user);
        return $this->view->fetch();
    }

    /**index
     * 退出登陆
     *
     * @return void
     */
    public function out_login()
    {
         //退出本站
         $this->auth->logout();
         $this->success('退出登陆');
    }

    
    /* 
    * @Description: 公众号测试登录可以直接用获取用户信息来（get_user方法已实现此方法）
    * @return: 
    */     
    public function login()
    {
        $url = $this->request->domain().'/index/index/code';
        $app = $this->get_wx_gzh_app();
        $app->oauth->scopes(['snsapi_userinfo'])->redirect($url);

        //这里不一定是return，如果你的框架action不是返回内容的话你就得使用
        $oauth->redirect()->send();

    }



    /* 
    * @Description: 公众号获取code
    * @return: 
    */   
    public function code()
    {
        $app = $this->get_wx_gzh_app();
        $oauth = $app->oauth;
       
        $user = $oauth->user();

        Session::set('wechat_user',$user->original);//获取到用户信息 自己可以存储
        // halt($user->original);//可以自己打印看下

        // $user = Session::get('wechat_user');

        $Xiaohe = new Xiaohe;
        // halt($user);
        $Xiaohe->update_user_data($user,Session::get('sharer'));
        $user_data = $Xiaohe->openid_get_user($user['openid']);


        
        //授权后挑战到那个地址
        $re_url = Session::get('re_url');
        if($re_url){
            Session::set('re_url',null);
            header("Location: ".$this->request->domain().$re_url);
        }else{
            header("Location: ".$this->request->domain()."/index/index/bind_student");
        }

    }


    public function test_send_msg()
    {
        # code...
        $this->get_user('/index/index/test_send_msg');
        $Template = new \app\api\controller\Template();
        $res = $Template->test_send_parent_template($this->auth->id);
        if($res){
            $this->success('发送成功！，可正常收到微信模版消息',"/index/index/bind_student");
        }else{
            $url = "/index/index/index";
            // $url = 'http://weixin.qq.com/r/BBKXj6HEr-zQreXs90cW';

            $this->error('发送失败,请关注公众号',$url);
        }
        header("Location: ".$this->request->domain()."/index/index/bind_student");

    }


    /**
     * 测试发送模版消息
     *
     * @param string $com_openid 微信公众号的openid
     * @param string $keyword1 参数1
     * @param [type] $keyword2 参数2
     * @param string $path 跳转小程序路径
     * @return void
     */
    public function test_send_template($com_openid='o0kt76ZCpj8g2HhO8IctpJIwWyu4',$keyword1=null,$keyword2="校门",$keyword3="chikare",$url=null,$name=null)
    {

        if(!$keyword1){
            $keyword1 = date('Y年m月d号H:i:s');
        }

        if(!$url){
            $url = 'http://www.hellomida.com/';
        }

        if(!$name){
            $name = 'XX';
        }
        $app = $this->get_wx_gzh_app();    
        $data = $app->template_message->send([
            'touser' => $com_openid,//微信openid,
            'template_id' => 'OdD8uIe3rLvIhiQD9NbcT-mORtUUxH2ouSexTfcYOBM',
            'url' => $url,//点击模版消息打开的页面地址
     
            'data' => [
                'first' =>['刷卡成功，祝福宝贝（'.$name.'）健康快乐','#173177'],
                'keyword1' =>[$keyword1,'#223177'],//刷卡时间
                'keyword2' =>[$keyword2,'#333177'],//刷卡地点
                'keyword3' =>[$keyword3,'#173177'],//持卡人
                'remark' =>['请忽略本条测试信息','#173199'],

            ],
        ]);
        if($data['errmsg']=='ok'){
            $this->success('发送成功！，可正常收到微信模版消息','/');
        }else{
            $this->error('发送失败'.$data['errmsg']);
        }
    }


    public function get_jssdk($url=null)
    {
        $app = $this->get_wx_gzh_app();
        $url = $this->request->domain().'/index/index/ucenter_zc';
        // halt($url);
        $app->jssdk->setUrl($url);
        // halt($url);
        $config = $app->jssdk->buildConfig(['startRecord', 'stopRecord', 'uploadVoice', 'onVoiceRecordEnd','downloadVoice','playVoice'],false,false,false,$url);

        return $config;
        // $app->js->setUrl($url);
        // $app->js->config(['updateAppMessageShareData','updateTimelineShareData'], $debug = false, $beta = false, $json = true); 
        //   halt($config);
    }

    
}
